﻿using Microsoft.Azure.Documents.Client;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Model.DocumentDB
{
    /// <summary>Base class for every view model using a <see cref="DocumentClient"/>.</summary>
    public abstract class DocumentClientViewModelBase<PARENT> : INotifyPropertyChanged
        where PARENT : class
    {
        /// <summary>Raised when a property is changed.</summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>Constructor.</summary>
        /// <param name="client">Client shared among different models.</param>
        /// <param name="parent">Parent of the model.</param>
        protected DocumentClientViewModelBase(DocumentClient client, PARENT parent)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }
            if (parent == null)
            {
                throw new ArgumentNullException("parent");
            }

            Client = client;
            Parent = parent;
        }

        /// <summary>Construct a model from account credentials.</summary>
        /// <param name="id">ID of the account.</param>
        /// <param name="authKey">Authorization key to access the account.</param>
        /// <param name="parent">Parent of the model.</param>
        protected DocumentClientViewModelBase(string id, string authKey, PARENT parent)
            : this(CreateClient(id, authKey), parent)
        {
        }

        /// <summary>Document client to the DocumentDB API.</summary>
        protected DocumentClient Client { get; private set; }

        /// <summary>Parent model.</summary>
        protected PARENT Parent { get; private set; }

        /// <summary>Raises the <see cref="PropertyChanged"/> event.</summary>
        /// <param name="propertyName">Name of the property.</param>
        protected void OnPropertyChanged(string propertyName)
        {
            if (string.IsNullOrWhiteSpace(propertyName))
            {
                throw new ArgumentNullException("propertyName");
            }

            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        private static DocumentClient CreateClient(string id, string authKey)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                throw new ArgumentNullException("id");
            }
            if (string.IsNullOrWhiteSpace(authKey))
            {
                throw new ArgumentNullException("authKey");
            }

            var endpoint = new Uri("https://" + id + ".documents.azure.com:443/");

            return new DocumentClient(endpoint, authKey);
        }
    }
}